
#include <cstring>
//#include <set>
#include <vector>
#include <string>
#include <algorithm>

#include "funcs.h"

struct bind_t
{
	int playerid;
	int keys;
	std::string cmd;

	bind_t() 
	{}
	bind_t(int id, int k, const char *c)
		:playerid(id), keys(k), cmd(c)
	{}

};

bool operator<(const struct bind_t &b1, const struct bind_t &b2)
{
	return(b1.playerid < b2.playerid && b1.keys < b2.keys);
}

bool operator==(const struct bind_t &b1, const struct bind_t &b2)
{
	return(b1.playerid == b2.playerid && b1.keys == b2.keys && b1.cmd == b2.cmd);
}

using namespace std;

typedef vector<struct bind_t> binds_t;


static binds_t binds_arr;



int add_bind(int playerid, int key, const char *cmd)
{
	if(playerid < 0 || playerid >= 500) return 0;
	struct bind_t temp_bind(playerid, key, cmd);
	/*
	temp_bind.playerid = playerid;
	temp_bind.keys = key;
	temp_bind.cmd = cmd;
	*/
	if(binds_arr.empty() || find(binds_arr.begin(), binds_arr.end(), temp_bind) == binds_arr.end())
	{
		binds_arr.push_back(temp_bind);
		return 1;
	}
	return 0;
}

int check_binds(int playerid, int newkeys, int oldkeys)
{
	if(binds_arr.empty())
		return 0;
	for(binds_t::iterator it = binds_arr.begin(), en = binds_arr.end();
		it != en;
		++it)
	{
		if(playerid == it->playerid)
		{
			int keys = it->keys;
			if(((newkeys & keys) == keys) && ((oldkeys & keys) != keys))
			{
				exec_onplayercommandtext(playerid, it->cmd.c_str());
			}
		}
	}
	return 1;
}

int del_bind(int playerid, int key)
{
	if(playerid < 0 || playerid >= 500) return 0;
	if(binds_arr.empty())
		return 0;
	for(binds_t::iterator it = binds_arr.begin(), en = binds_arr.end();
		it != en;
		++it)
	{
		if(playerid == it->playerid && key == it->keys)
		{
			binds_arr.erase(it);
			//return 1;
		}
	}
	return 1;
}


int binds_bound()
{
	return binds_arr.size();
}

bool get_bind_by_index(int index, int *playerid, int *keys, string& cmd)
{
	try
	{
		struct bind_t& got = binds_arr.at(index);
		*playerid = got.playerid;
		*keys = got.keys;
		cmd = got.cmd;
	}
	catch(...)
	{
		return 0;
	}
	return 1;
}

